import { onBeforeUnmount, onMounted, ref, watch } from 'vue'

export default function(props, collapseContainer, resizeBar) {
  const width = ref(props.minWidth)
  const maxWidth = ref(0)
  const minExistWidth = ref(5)
  const maxHeight = ref(0)
  let mutationObserver = null
  const methods = {
    /**
     * 监听dom大小改变
     * @param {*} dom
     */
    handleResize(dom) {
      width.value = dom.offsetWidth
    },
    /**
     * 主动折叠/收缩
     * 1 => 展开左侧, 0 => 恢复默认, -1 => 收缩左侧
     * @param {*} direction
     */
    collapse(direction) {
      switch (direction) {
        case 1:
          width.value = maxWidth.value - minExistWidth.value
          break
        case -1:
          width.value = minExistWidth.value
          break
        case 0:
        default:
          width.value = props.minWidth
          break
      }
    },
    updateDimensions() {
      if (collapseContainer.value) {
        maxWidth.value = collapseContainer.value.offsetWidth
        maxHeight.value = collapseContainer.value.offsetHeight
        width.value = props.minWidth
      }
    },
    initObserver() {
      const observerOptions = {
        childList: false,
        attributes: true,
        subtree: false
      }
      mutationObserver = new MutationObserver((entries) => {
        methods.handleResize(entries[0].target)
      })
      mutationObserver.observe(resizeBar.value, observerOptions)
    },
    pxToPercent(px) {
      if (typeof px === 'string') {
        return px;
      } else {
        return px + 'px';
      }
    }
  }
  watch(() => props.minWidth, () => {
    methods.updateDimensions()
  }, { immediate: true })

  onMounted(() => {
    methods.initObserver()
    methods.updateDimensions()
  })

  onBeforeUnmount(() => {
    if (mutationObserver) {
      mutationObserver.disconnect()
    }
  })
  return {
    maxHeight,
    width,
    minExistWidth,
    maxWidth,
    methods
  }
}
